
export default class IdleService {
  constructor (timeout = parseInt(document.querySelector('meta[name="logout_time"]').content) * 1000) { // 10分钟
    this.timeout = timeout
    this.idleTimer = null
    this.onTimeoutCallbacks = []
    this.onExpiredCallbacks = []
    this.eventHandler = this.updateExpireTime.bind(this)
    this.startTracking()
  }
  startTracking () {
    this.updateExpireTime()
    window.addEventListener('mousemove', this.eventHandler)
    window.addEventListener('keypress', this.eventHandler)
    window.addEventListener('scroll', this.eventHandler)
    window.addEventListener('click', this.eventHandler)
    window.addEventListener('touchstart', this.eventHandler)
  }
  stopTracking () {
    window.removeEventListener('mousemove', this.eventHandler)
    window.removeEventListener('keypress', this.eventHandler)
    window.removeEventListener('scroll', this.eventHandler)
    window.removeEventListener('click', this.eventHandler)
    window.removeEventListener('touchstart', this.eventHandler)
    clearTimeout(this.idleTimer)
    console.log('大计时器终止aaaaa')
  }

  updateExpireTime () {
    clearTimeout(this.idleTimer)
    this.idleTimer = setTimeout(() => {
      this.onTimeoutCallbacks.forEach(cb => cb())
      // this.idleTimer = setTimeout(() => {
      //   this.onExpiredCallbacks.forEach(cb => cb())
      // }, 30000) // 30秒后强制退出
      // this.onExpiredCallbacks.forEach(cb => cb())
    }, this.timeout)
  }

  onTimeout (callback) {
    this.onTimeoutCallbacks.push(callback)
  }

  onExpired (callback) {
    this.onExpiredCallbacks.push(callback)
  }

  reset () {
    clearTimeout(this.idleTimer)
    this.updateExpireTime()
  }
}
